﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace WPFSample.DuplicateUniformGridSample
{
    public class UniformGridAlmost : Panel
    {
        public int Columns
        {
            get { return (int)GetValue(ColumnsProperty); }
            set { SetValue(ColumnsProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Columns.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ColumnsProperty =
            DependencyProperty.Register("Columns", typeof(int), typeof(UniformGridAlmost), new FrameworkPropertyMetadata(1, FrameworkPropertyMetadataOptions.AffectsMeasure));

        public int Rows
        {
            get
            {
                return (this.InternalChildren.Count + this.Columns - 1) / this.Columns;
            }
        }

        protected override Size MeasureOverride(Size availableSize)
        {
            Size sizeChild = new Size(availableSize.Width / this.Columns, availableSize.Height / this.Rows);

            double maxWidth = 0;
            double maxHeight = 0;
            foreach (UIElement child in this.InternalChildren)
            {
                child.Measure(sizeChild);

                maxWidth = Math.Max(maxWidth, child.DesiredSize.Width);
                maxHeight = Math.Max(maxHeight, child.DesiredSize.Height);
            }

            return new Size(this.Columns * maxWidth, this.Rows * maxHeight);
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            Size sizeChild = new Size(finalSize.Width / this.Columns, finalSize.Height / this.Rows);
            for (int i = 0; i < this.InternalChildren.Count; i++)
            {
                int row = i / this.Columns;
                int col = i % this.Columns;

                Rect rectChild = new Rect(new Point(col * sizeChild.Width, row * sizeChild.Height), sizeChild);
                this.InternalChildren[i].Arrange(rectChild);
            }

            return finalSize;
        }
    }
}
